package com.farm.wcp.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.farm.core.page.ViewMode;
import com.farm.parameter.FarmParameterService;
import com.farm.wcp.util.AntiXSS;
import com.farm.web.WebUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wts.exam.domain.PaperCard;
import com.wts.exam.domain.Room;
import com.wts.exam.domain.ex.PaperUnit;
import com.wts.exam.service.ExamtypeServiceInter;
import com.wts.exam.service.PaperServiceInter;
import com.wts.exam.service.PapercardServiceInter;
import com.wts.exam.service.RoomServiceInter;

/**
 * 考试
 * 
 * @author autoCode
 * 
 */
@RequestMapping("/webpaper")
@Controller
public class PaperWebController extends WebUtils {
	@Resource
	private PaperServiceInter paperServiceImpl;
	@Resource
	private ExamtypeServiceInter examTypeServiceImpl;
	@Resource
	private RoomServiceInter roomServiceImpl;
	@Resource
	private PapercardServiceInter paperCardServiceImpl;
	private static final Logger log = Logger.getLogger(PaperWebController.class);

	public static String getThemePath() {
		return FarmParameterService.getInstance().getParameter("config.sys.web.themes.path");
	}

	/***
	 * 答题卡
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/paperCard")
	public ModelAndView index(String paperid, String roomId, HttpServletRequest request, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			Room room = roomServiceImpl.getRoomEntity(roomId);
			// 进入答题室：1.判断时间，判断人员
			if (!roomServiceImpl.isLiveTimeRoom(room)) {
				throw new RuntimeException("该房间不可用，未到答题时间!");
			}
			if (getCurrentUser(session) == null) {
				throw new RuntimeException("请先登陆系统!");
			}
			if (!roomServiceImpl.isUserAbleRoom(room.getId(), getCurrentUser(session))) {
				throw new RuntimeException("当前用户无进入权限!");
			}
			PaperUnit paper = paperServiceImpl.getPaperUnit(paperid);
			// 创建答题卡
			PaperCard card = paperCardServiceImpl.creatOrGetPaperCard(paperid, roomId, getCurrentUser(session));
			//从答题卡中加载用户答案
			paperCardServiceImpl.loadCardVal(paper, card);
			if (!card.getPstate().equals("1")) {
				throw new RuntimeException("该试卷非答题状态!");
			}
			return view.putAttr("paper", paper).putAttr("room", room).putAttr("card", card)
					.returnModelAndView(getThemePath() + "/paper/paperCard");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnModelAndView(getThemePath() + "/error");
		}
	}

	/**
	 * 暂存用户一道题答案
	 * 
	 * @return
	 */
	@RequestMapping("/saveSubjectVal")
	@ResponseBody
	public Map<String, Object> saveSubjectVal(String paperid, String roomid, String jsons, HttpSession session) {
		try {
			ViewMode page = ViewMode.getInstance();
			JsonParser parse = new JsonParser(); // 创建json解析器
			JsonObject json = (JsonObject) parse.parse(jsons);
			String versionid = json.get("versionid").getAsString();
			String answerid = json.get("answerid").getAsString();
			String value = json.get("value").getAsString();
			if (StringUtils.isNotBlank(value)) {
				value = AntiXSS.replaceHtmlCode(value);
			}
			boolean isAnswer = paperCardServiceImpl.savePaperCardVal(paperid, roomid, versionid, answerid, value,
					getCurrentUser(session));
			return page.putAttr("isAnswer", isAnswer).returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 暂存试卷答案
	 * 
	 * @return
	 */
	@RequestMapping("/savePaperVal")
	@ResponseBody
	public Map<String, Object> savePaperVal(String paperid, String roomid, String jsons, HttpSession session) {
		try {
			ViewMode page = ViewMode.getInstance();
			JsonParser parse = new JsonParser(); // 创建json解析器
			JsonArray jsonArray = (JsonArray) parse.parse(jsons);
			for (JsonElement obj : jsonArray) {
				JsonObject sjonObj = obj.getAsJsonObject();
				String versionid = sjonObj.get("versionid").getAsString();
				String answerid = sjonObj.get("answerid").getAsString();
				String value = sjonObj.get("value").getAsString();
				if (StringUtils.isNotBlank(value)) {
					value = AntiXSS.replaceHtmlCode(value);
				}
				paperCardServiceImpl.savePaperCardVal(paperid, roomid, versionid, answerid, value,
						getCurrentUser(session));
			}
			return page.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/submitPaper")
	public ModelAndView submitPaper(String cardId, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			paperCardServiceImpl.finishExam(cardId, getCurrentUser(session));
			return view.putAttr("MESSAGE", "试卷提交成功!").returnModelAndView(getThemePath() + "/message");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnModelAndView(getThemePath() + "/error");
		}
	}
}
